package com.yinhe.music.yhmusic.personal;

import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.type.person.BaseInfo;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.IBaseModel;
import com.yinhe.music.yhmusic.base.IBaseView;
import com.yinhe.music.yhmusic.http.StatusCode;
import com.yinhe.music.yhmusic.network.response.Response;
import com.yinhe.music.yhmusic.network.response.ResponseTransformer;

import java.util.List;

/**
 * @author 何晓华
 */
public class PersonPresenter<M extends IBaseModel, V extends IBaseView> extends BasePresenter<M, V>
        implements PersonContract.IPersonPresenter {

    @Override
    public void getUserInfo() {
        PersonContract.IPersonView mView = (PersonContract.IPersonView) getView();
        if (mView == null) {
            return;
        }

        addSubscription(mModel.reqUserInfo()
                .compose(ResponseTransformer.handleResult())
                .compose(schedulerProvider.applySchedulers())
                .subscribe(mView::setUserUI, mView::showMessage));
    }

    @Override
    public void createSongMenu(String name, List<Integer> songIdList, int type) {
        if (getView() == null) {
            return;
        }

        getView().showLoading();

        addSubscription(mModel.createUserSongMenu(name)
                .compose(schedulerProvider.applySchedulers())
                .subscribe(baseInfo -> {
                    handleCreateResp(baseInfo, songIdList, type);
                }, throwable -> {
                    getView().hideLoading();
                    getView().showMessage(throwable);
                }));
    }

    protected void handleCreateResp(Response<BaseInfo> baseInfo, List<Integer> songIdList, int type) {
        if (baseInfo.getCode() == StatusCode.REQUEST_SUCCESS) {
            getView().showToast(baseInfo.getMsg());
            RxBus.get().post(RxBusEventType.SongMenu.CREATE_MENU, RxbusNullObject.INSTANCE);
        } else {
            getView().showToast(baseInfo.getMsg());
        }
        getView().hideLoading();
    }
}
